﻿using System;
using Space2D_Utils;

namespace Space2D_Core
{
	[Serializable]
	public class Ship : PhysicalObject
	{
		public Ship(string name, double mass, double fuelMass, double fuelSpeed, double enginePower)
			: base(name, mass)
		{
			FuelMass = fuelMass;
			FuelSpeed = fuelSpeed;
			EnginePower = enginePower;
			EngineDirection = new Vector2d(1, 0);
			EngineAcceleration = new Vector2d(0, 0);
			EnginePowerMultiplier = 0.0;
		}

		public override void Init(Vector2d acceleration, Vector2d speed, Vector2d position)
		{
			base.Init(acceleration, speed, position);
		}

		public override void Tick(int ms)
		{
			UpdateEngine();

			base.Tick(ms);
		}

		public override Vector2d GetTotalAcceleration()
		{
			return base.GetTotalAcceleration() + EngineAcceleration;
		}

		public void SetEnginePower(Vector2d engineDirection, double enginePowerMultiplier)
		{
			EngineDirection = engineDirection.Normalized();

			EnginePowerMultiplier = enginePowerMultiplier;

			if (EnginePowerMultiplier > 1.0)
			{
				EnginePowerMultiplier = 1.0;
			}
		}

		private void UpdateEngine()
		{
			if (EnginePowerMultiplier > 0.0)
			{
				double fuelMass = 2 * EnginePowerMultiplier * EnginePower / (FuelSpeed * FuelSpeed);

				if (fuelMass > FuelMass)
				{
					fuelMass = FuelMass;
				}

				FuelMass -= fuelMass;

				EngineAcceleration = (EngineDirection * fuelMass * FuelSpeed / (FuelMass + Mass));

				/*PhysicalObject fuel = new PhysicalObject("fuel", fuelMass);
				fuel.Init(new Vector2d(0, 0), EngineDirection * 1, Position);

				WorldManager.Register(fuel);*/
			}
			else
			{
				EngineAcceleration = new Vector2d(0, 0);
			}
		}

		public double FuelMass { get; private set; }
		public double FuelSpeed { get; private set; }
		public double EnginePower { get; private set; }
		public double EnginePowerMultiplier { get; private set; }
		public Vector2d EngineDirection { get; private set; }
		public Vector2d EngineAcceleration { get; private set; }
	}
}